<?php

namespace app\admin\service\channel;

use think\facade\Request;
use tmcore\base\BaseService;
use app\common\model\setting\Config as ConfigModel;
use tmcore\services\ConfigService;

class WechatService extends BaseService
{
    /**
     * 获取微信公众号渠道配置
     * @return array
     */
    public static function getWechatConfig(): array
    {
        $config = com_get_config( 'wx_oa_channel','sys');
        $domain = Request::domain();
        return [
            'name' => $config['name']??'',
            'original_id' => $config['original_id']??'',
            'qr_code' => $config['qr_code']??'',
            'app_id' => $config['app_id']??'',
            'app_secret' => $config['app_secret']??'',
            'server_url' => request()->domain() . '/http/wechat/auth',
            'verify_file_url' => $config['verify_file_url']??'',
            'token' => $config['token']??'',
            'encoding_aes_key' => $config['encoding_aes_key']??'',
            'encryption_type' => $config['encryption_type']??1,
            'business_domain' => $domain,
            'js_domain' => $domain,
            'auth_domain' => $domain,
        ];
    }

    /**
     * 设置微信公众号渠道配置
     * @param array $params
     * @return bool
     */
    public static function setWechatConfig(array $params)
    {
        $data = [
            'name' => $params['name']??'', // 公众号名称
            'original_id' => $params['original_id']??'', // 原始id
            'qr_code' => $params['qr_code']??'', // 二维码
            'app_id' => $params['app_id']??'', // appID
            'app_secret' => $params['app_secret']??'', // appSecret
            'verify_file_url' => $params['verify_file_url']??'', // 网页授权时的微信校验文件
            'token' => $params['token']??'', // token
            'encoding_aes_key' => $params['encoding_aes_key']??'', // EncodingAESKey
            'encryption_type' => isset($params['encryption_type'])?intval($params['encryption_type']):'', // 加密方式：1-明文 2-兼容 3-安全
        ];

        $res = ConfigModel::where(['name' => 'wx_oa_channel'])->update(['value' => json_encode($data, 320)]);

        (new ConfigService)->setConfig('create', 'sys', 'wx_oa_channel');

        return $res !== false;
    }
}